<script>

import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "FivePage",
  data(){
    return{
      error:'',

      allPlanList:[],
      allAnswers:[],

      planList:[],
      cityList:[],
      currentCityIndex:0,
      currentPlanIndex:0,

      marketList:[],
      lineList:null,
      hotelPoint:null,

      posChange:{
        chosing:false,
        index1:null,
        index2:null
      }
    }
  },
  watch:{
    //初始化和传入数值时
    allPlanList:{
      handler(newVal){
        //选取所有城市
        const uniqueCities = new Set(newVal.map(plan => plan.cityName));
        this.cityList = Array.from(uniqueCities);
        //筛选出planList
        this.planList = newVal.filter(plan => plan.cityName === this.cityList[this.currentCityIndex])
        //更新地图
        this.updateMap()
      },
      deep:true
    },
    //改变选择城市时
    currentCityIndex(newVal){
      this.currentPlanIndex = 0;
      //筛选出planList
      this.planList = this.allPlanList.filter(plan => plan.cityName === this.cityList[newVal])
      //更新地图
      this.updateMap();
    },
    //改变计划时
    currentPlanIndex(){
      this.updateMap()
    }

  },
  mounted() {
    //AAA运行时注释
    /*this.allPlanList = [{"planId":1,"planName":"武汉一日游","cityName":"武汉","startTime":"2023-12-10-1","endTime":"2023-12-10-2","hotelName":"如家酒店（武汉大学店）","hotellat":30.5834,"hotellng":114.321,"empty":"default"},{"planId":3,"planName":"武汉两日游","cityName":"武汉","startTime":"2023-12-10-0","endTime":"2023-12-11-2","hotelName":"如家酒店（武汉大学店）","hotellat":30.5888,"hotellng":114.321,"empty":"default"},{"planId":4,"planName":"广州一日游","cityName":"广州","startTime":"2023-12-10-0","endTime":"2023-12-10-1","hotelName":"如家酒店(广州大学店)","hotellat":30.5833,"hotellng":114.371,"empty":"default"}]
    this.allAnswers = [{"planId":1,"answerList":[{"answerId":1,"planId":1,"name":"武汉大学","ifDeleted":0,"answerIndex":1,"lat":30.5811,"lng":114.311},{"answerId":2,"planId":1,"name":"银泰","ifDeleted":0,"answerIndex":2,"lat":30.5822,"lng":114.301},{"answerId":3,"planId":1,"name":"不想去删掉","ifDeleted":1,"answerIndex":3,"lat":30.5833,"lng":114.321},{"answerId":4,"planId":1,"name":"群光","ifDeleted":0,"answerIndex":4,"lat":30.5844,"lng":114.321}]},{"planId":3,"answerList":[{"answerId":5,"planId":3,"name":"武汉大学","ifDeleted":0,"answerIndex":1,"lat":30.5855,"lng":114.321},{"answerId":6,"planId":3,"name":"不想去删掉","ifDeleted":1,"answerIndex":2,"lat":30.5866,"lng":114.321},{"answerId":7,"planId":3,"name":"不想去删掉","ifDeleted":1,"answerIndex":3,"lat":30.5877,"lng":114.321},{"answerId":8,"planId":3,"name":"群光","ifDeleted":0,"answerIndex":4,"lat":30.5888,"lng":114.321}]},{"planId":4,"answerList":[{"answerId":9,"planId":4,"name":"不想去删掉","ifDeleted":1,"answerIndex":1,"lat":30.5899,"lng":114.321},{"answerId":10,"planId":4,"name":"不想去删掉","ifDeleted":1,"answerIndex":2,"lat":30.5855,"lng":114.321}]}]
*/


    this.initMap()
    this.$EventBus.$on('initPlanAndAnswer',(e)=>{
      this.allPlanList = JSON.parse(JSON.stringify(e)).planList;
      this.allAnswers = JSON.parse(JSON.stringify(e)).allAnswers;

      for (const allAnswer of this.allAnswers) {
        allAnswer.answerList.sort(function (a, b){
          return a.answerIndex - b.answerIndex;
        })
      }
    })
    this.$EventBus.$on('newPlanAnswerSet',(e)=>{
      this.handleNewPlan(JSON.parse(JSON.stringify(e)).newPlan, JSON.parse(JSON.stringify(e)).newPlanAnswerList)
    })
  },

  methods:{
    //地图初始化
    initMap(){
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 11, // 初始化地图级别
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });
          })
          .catch((e) => {
            console.log(e);
          });
    },
    //更新地图
    updateMap(){
      const hotel = {
        lng:this.planList[this.currentPlanIndex].hotelLng,
        lat:this.planList[this.currentPlanIndex].hotelLat,
        name:this.planList[this.currentPlanIndex].hotelName
      }
      const answers = this.allAnswers.find(answerStru => answerStru.planId === this.planList[this.currentPlanIndex].planId).answerList
      let positions = []
      for (const answer of answers) {
        if (answer.ifDeleted === 0){
          positions.push({
            lng:answer.lng,
            lat:answer.lat,
            name:answer.name
          })
        }
      }
      console.log(hotel)
      let that = this;
      //地图动画
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            if (this.map === null || this.map === undefined){
              setTimeout(()=>this.updateMap(),1000)
            }
            this.map.remove(that.marketList)
            that.marketList = []
            for (const position of positions) {
              that.marketList.push(new AMap.Marker({
                position: new AMap.LngLat(position.lng,position.lat),
                title:position.name
              }))
            }
            that.hotelPoint = hotel
            that.marketList.push(new AMap.Marker({
              offset: new AMap.Pixel(-16, -16),
              icon:'/hotel.png',
              position:new AMap.LngLat(hotel.lng,hotel.lat),
              title:hotel.name
            }))
            this.map.clearMap()
            this.map.add(that.marketList);
            this.map.setFitView();

          })
          .catch((e) => {
            console.log(e);
          });
    },
    //画线
    drawLines(points){
      let that = this
      AMapLoader.load({
        key: "dd2617cca23d86965b37a281144bfa49", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            if (that.lineList !== null){
              this.map.remove(that?.lineList)
            }
            var path = []
            for (const point of points) {
              path.push(new AMap.LngLat(point.lng,point.lat))
            }
            path.push(new AMap.LngLat(that.hotelPoint.lng,that.hotelPoint.lat) )
            that.lineList = new AMap.Polyline({
              path:path,
              borderWeight:1,
              strokeColor:'blue',
              lineJoin:'miter'
            })
            this.map.add(that.lineList)
            this.map.setFitView(that.lineList)
          })
          .catch((e) => {
            console.log(e);
          });
    },


    //两个目标点换位
    exchangeTwoAnswers(planId, index1, index2){
      window.bound?.exchangeTwoAnswers({
        planId:planId,
        index1:index1,
        index2:index2
      })
    },
    //某个目标点置空
    dontGo(answerId){
      window.bound?.dontGo(answerId);
    },
    //处理新增计划，有则覆盖，无则插入，最后选中
    handleNewPlan(newPlan, newPlanAnswerList){
      const newPlanStruc = {
        planId:newPlan.planId,
        answerList:newPlanAnswerList
      }
      setTimeout(()=>{
        if (this.allAnswers.includes(answerS => answerS.answerId === newPlan.planId)){
          //包含这个元素，替换
          this.allAnswers = this.allAnswers.filter(answerStru => answerStru.answerId !== newPlan.planId)
          this.allPlanList = this.allPlanList.filter(plan => plan.planId !== newPlan.planId)
        }else {
          this.allAnswers.push(newPlanStruc)
        }
        this.allPlanList.push(newPlan)
      },1000)
      console.log(newPlanStruc)
    },

    //空闲管理
    freeLockAnswer(ansId){
      for (const allAnswer of this.allAnswers) {
        for (const answer of allAnswer.answerList) {
          if (answer.answerId === ansId){
            answer.ifDeleted = (answer.ifDeleted===0)?1:0;
            this.dontGo(ansId)
            this.updateMap()
          }
        }
      }
    },

    //返回出行周期
    getPlanTime(time){
      let tmp = null;
      switch (Number(time?.slice(-1))){
        case 0: tmp = '上午';
          break;
        case 1: tmp = '下午';
          break;
        case 2: tmp = '晚上';
          break;
      }
      return time?.slice(0, 10)+'-'+tmp
    },
    //返回answer的时间
    getAnswerTime(startTime,index){
      const dayAdd = Math.floor(((Number(startTime?.slice(-1))+index-1)/3))
      console.log('starttime'+startTime)
      console.log('starttimeslice'+startTime.slice(-1))
      console.log('index'+index)
      console.log('dayadd'+dayAdd)
      console.log('end')

      const dayDetail = ((Number(startTime?.slice(-1))+index-1)%3)
      let resultDayDetail = null;
      switch (dayDetail){
        case 0: resultDayDetail = '上午';
          break;
        case 1: resultDayDetail = '下午';
          break;
        case 2: resultDayDetail = '晚上';
          break;
      }
      const day = startTime?.slice(0, 10)
      const date = new Date(Date.parse(day));
      date.setDate(date.getDate() + dayAdd);
      const resultDay = date.toISOString().slice(0, 10);

      return resultDay+'-'+resultDayDetail
    },
    //要不要显示今日路线
    checkTodayBtn(answer,time){
      if (answer.answerIndex === this.allAnswers.find(answerStruc => answerStruc.planId === this.planList[this.currentPlanIndex].planId)?.answerList.length){
        return true
      }
      if (time.slice(-2)==='晚上'){
        return true
      }
    },
    //显示今天路线
    checkThisDayLine(answer,time){
      //返回要画的点
      //当天内的answer
      let todayAllAnswer = []
      const answerList = this.allAnswers.find(answerStruc => answerStruc.planId === this.planList[this.currentPlanIndex].planId)?.answerList
      if (time.slice(-2)==='晚上'){
        for (let i = 0; i < 3; i++) {
          const toFindIndex = answer.answerIndex - i;
          if (toFindIndex > 0){
            todayAllAnswer.push(answerList.find(ans => ans.answerIndex === toFindIndex))
          }
        }
      }else if (time.slice(-2)==='下午'){
        for (let i = 0; i < 2; i++) {
          const toFindIndex = answer.answerIndex - i;
          if (toFindIndex > 0){
            todayAllAnswer.push(answerList.find(ans => ans.answerIndex === toFindIndex))
          }
        }
      }else if (time.slice(-2)==='上午'){
        todayAllAnswer.push(answer)
      }
      //不为空闲的answer转化为点
      let points = [];
      for (const answer of todayAllAnswer) {
        if (answer.ifDeleted === 0){
          points.push({
            lng:answer.lng,
            lat:answer.lat,
            index:answer.answerIndex
          })
        }
      }
      //画图
      this.drawLines(points)
    },

    //换位
    posChangeIndex1(index1){
      this.posChange.chosing = true;
      this.posChange.index1 = index1;
    },
    posChangeIndex2(index2){
      this.exchangeTwoAnswers(this.planList[this.currentPlanIndex].planId,this.posChange.index1,index2);
      this.posChange.chosing = false;
      //前端交换位置
      let answerlist = this.allAnswers.find(answerStruc => answerStruc.planId === this.planList[this.currentPlanIndex].planId)?.answerList
      const answer1 = JSON.parse(JSON.stringify(answerlist.find(answer => answer.answerIndex === this.posChange.index1)))
      const answerI1 = answerlist.indexOf(answerlist.find(answer => answer.answerIndex === this.posChange.index1));
      const answer2 = JSON.parse(JSON.stringify(answerlist.find(answer => answer.answerIndex === index2)))
      const answerI2 = answerlist.indexOf(answerlist.find(answer => answer.answerIndex === index2));
      answerlist[answerI1].name = answer2.name;
      answerlist[answerI1].lng = answer2.lng;
      answerlist[answerI1].lat = answer2.lat;
      answerlist[answerI2].name = answer1.name;
      answerlist[answerI2].lng = answer1.lng;
      answerlist[answerI2].lat = answer1.lat;
    },
    cancelPosChange(){
      this.posChange.chosing = false;
    }

  }
}
</script>

<template>
  <div>
    <div style="position: absolute; right: 0; bottom: 0; width: 50%; height: 50%; overflow-y: scroll;">{{ error }}</div>
    <!--选择城市，选择计划-->
    <div class="choose-city-container">
      <div class="target-title1">选择计划</div>
      <div class="two-container two-container-col">
        <div class="city-plan-line">
          <div>选择城市：</div>
          <el-select size="small" style="width: 160px" v-model="currentCityIndex" :placeholder="cityList[currentCityIndex]">
            <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </div>
        <div class="city-plan-line">
          <div>选择计划：</div>
          <el-select size="small" style="width: 160px" v-model="currentPlanIndex" :placeholder="planList[currentPlanIndex]?.planName">
            <el-option
                v-for="(item, index) in planList"
                :key="index"
                :label="item.planName"
                :value="index">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <div class="current-plan-container">
      <div class="target-title1">当前计划</div>
      <div class="two-container two-container-col">
        <div class="city-plan-line">
          <div style="width: 200px" class="scroll-x">计划名：{{planList[currentPlanIndex]?.planName}}</div>
          <div style="font-size: 14px; width: 200px; text-align: right" class="scroll-x">出行时间：{{getPlanTime(planList[currentPlanIndex]?.startTime)}}</div>
        </div>
        <div class="city-plan-line">
          <div style="font-size: 14px;width: 200px" class="scroll-x">住宿:{{planList[currentPlanIndex]?.hotelName}}</div>
          <div style="font-size: 14px;width: 200px; text-align: right" class="scroll-x">结束时间：{{getPlanTime(planList[currentPlanIndex]?.endTime)}}</div>
        </div>

      </div>
    </div>
    <!--当前计划-->
    <div class="plan-answer-container">
      <div class="target-title1">当前旅行方案</div>
      <!--时间顺序-->
      <div class="answer-list">
        <div class="answer-line">
          <div class="time-item all-line-item">时间</div>
          <div class="target-item all-line-item">目的地</div>
          <div class="delete-item all-line-item">空闲</div>
          <div class="line-item all-line-item">此日路线</div>
          <div class="pos-item all-line-item">换位</div>
        </div>
        <div class="answer-line" v-for="answer in allAnswers.find(answerStruc => answerStruc.planId === planList[currentPlanIndex].planId)?.answerList" :key="answer.answerId">
          <div style="font-size: 14px" class="scroll-x time-item all-line-item">{{getAnswerTime(planList[currentPlanIndex].startTime,answer.answerIndex)}}</div>
          <div class="target-item all-line-item scroll-x" style="justify-content: left" v-if="answer.ifDeleted === 0">{{answer.name}}</div>
          <div class="target-item all-line-item" style="color: #888;" v-else>空闲</div>
          <div class="delete-item all-line-item" v-if="answer.ifDeleted === 0"> <el-button size="small" type="warning" @click="freeLockAnswer(answer.answerId)" plain>设为空闲</el-button> </div>
          <div class="delete-item all-line-item" v-else> <el-button size="small" type="success" @click="freeLockAnswer(answer.answerId)" plain>重设想去</el-button> </div>
          <div class="line-item all-line-item"> <el-button size="small" type="primary" @click="checkThisDayLine(answer,getAnswerTime(planList[currentPlanIndex].startTime,answer.answerIndex))" plain v-if="checkTodayBtn(answer,getAnswerTime(planList[currentPlanIndex].startTime,answer.answerIndex))">查看</el-button> </div>
          <div class="pos-item all-line-item">
            <el-button size="small" @click="posChangeIndex1(answer.answerIndex)" v-if="!posChange.chosing" plain>选择</el-button>
            <el-button size="small" @click="cancelPosChange" v-if="posChange.chosing && answer.answerIndex === posChange.index1" type="success" plain>取消</el-button>
            <el-button size="small" @click="posChangeIndex2(answer.answerIndex)" v-if="posChange.chosing && answer.answerIndex !== posChange.index1" type="warning" plain>换位</el-button>
          </div>
        </div>
      </div>
    </div>
    <!--高德地图-->
    <div id="container" class="map-container">

    </div>
  </div>
</template>

<style scoped>
  .choose-city-container{
    position: absolute;
    left: 10px;
    right: 510px;
    bottom: 114px;
    height: 114px;
    border-bottom: 1px solid #ddd;
  }
  .current-plan-container{
    position: absolute;
    left: 10px;
    bottom: 6px;
    right: 510px;
    height: 100px;
  }
  .map-container{
    background-color: #eee;
    left: 10px;
    top: 20px;
    bottom: 240px;
    right: 510px;
    position: absolute;
  }
  .plan-answer-container{
    position: absolute;
    right: 0;
    top: 10px;
    bottom: 10px;
    width: 500px;
  }

  .current-plan-inner-container{
    position: absolute;
    left: 8%;
    right: 5%;
    top: 36px;
    bottom: 4px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  .target-title1{
    position: absolute;
    left: 4px;
    top: 4px;
    font-size: 16px;
    font-weight: bold;
  }
  .two-container{
    position: absolute;
    top: 30px;
    left: 12px;
    right: 12px;
    bottom: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .two-container-col{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  .city-plan-line{
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 90%;
  }
  .answer-list{
    position: absolute;
    top: 36px;
    bottom: 0;
    left: 2%;
    right: 2%;
    overflow-y: scroll;
  }
  .answer-line{
    width: 100%;
    display: flex;
    align-items: center;
    height: 40px;
    margin-bottom: 4px;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
  }
  .time-item{
    width: 23%;
  }
  .target-item{
    width: 25%;
  }
  .delete-item{
    width: 18%;
  }
  .line-item{
    width: 15%;
  }
  .pos-item{
    width: 14%;
  }
  .all-line-item{
    white-space: nowrap;
    align-items: center;
    display: flex;
    justify-content: center;
  }

</style>